package com.aiju.cash.ui.good.manager;

import android.content.Context;
import android.content.Intent;
import android.util.SparseArray;
import android.util.SparseIntArray;

import com.aiju.bean.Good;
import com.aiju.bean.GoodsType;
import com.aiju.cash.ui.billing.OrderActivity;
import com.aiju.common.db.GoodService;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.T;
import com.aiju.utils.Util;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 佐为
 * @date: 2016-12-21 13:35
 * @version: V1.0
 * @Description: 商品开单管理
 * <p>利用中介者模式</p>
 */
public class GoodManager {

    //商品列表
    private List<Good> goods = new ArrayList<>();

    //商品分类列表
    private List<GoodsType> goodsTypes = new ArrayList<>();

    //商品分类已选择的商品
    private SparseArray<Good> selectedGoods;

    //商品分类选择商品的数目
    private SparseIntArray selectedNumbers;

    //单例模式获取此对象
    private static volatile GoodManager instance;

    //购物车
    private ShopCart shopCartDialog;

    //上下午context
    private Context context;

    //商品数据库
    private GoodService goodService;

    //更新视图接口回调
    private List<OnChangeListener> listeners = new ArrayList<>();

    public void addOnChangeListener(OnChangeListener changeView) {
        listeners.add(changeView);
    }

    public void delete() {
        for (GoodsType type : goodsTypes) {
            List<Good> selectGoods = type.getSelectGoods();
            for (Good good : selectGoods) {
                goods.remove(good);
            }
            selectGoods.clear();
        }
    }

    public interface OnChangeListener {
        void changeView();
    }

    //单例
    public static GoodManager getInstance(Context context) {
        if (instance == null) {
            synchronized (GoodManager.class) {
                if (instance == null) {
                    instance = new GoodManager(context);
                }
            }
        }
        return instance;
    }

    public GoodManager(Context context) {
        this.context = context;
        selectedGoods = new SparseArray();
        selectedNumbers = new SparseIntArray();
        goodService = new GoodService(context);
    }

    public void setShopCartDialog(ShopCart shopCartDialog) {
        this.shopCartDialog = shopCartDialog;
    }

    /**
     * 跳转订单界面
     */
    public void startOrderActivity() {
        if (selectedGoods.size() == 0) {
            T.ToastShort("购物车为空");
            return;
        }
        Intent intent = new Intent(context, OrderActivity.class);
        context.startActivity(intent);
    }

    /**
     * 购物车
     *
     * @return
     */
    public ShopCart getShopCartDialog() {
        if (shopCartDialog == null) {
            shopCartDialog = new ShopCart(context);
        }
        return shopCartDialog.setLayoutParams().setSelectedGood(selectedGoods);
    }

    /**
     * 初始化商品
     *
     * @param goodsTypes
     */
    public void addGoodData(List<GoodsType> goodsTypes) {
        if (Util.isEmpty(goodsTypes)) {
            return;
        }
        reset();
        this.goodsTypes = goodsTypes;
        for (GoodsType goodsType : goodsTypes) {
            this.goods.addAll(goodsType.getGoodsList());
        }
        goodService.saveGood(goods);
    }

    /**
     * 商品数量加减
     *
     * @param good
     * @param refresh 是否刷新商品list
     */
    public void add(Good good, boolean refresh) {
        int groupCount = selectedNumbers.get(good.getTypeId());
        if (groupCount == 0) {
            selectedNumbers.append(good.getTypeId(), 1);
        } else {
            selectedNumbers.append(good.getTypeId(), ++groupCount);
        }

        Good selectGood = selectedGoods.get(good.getIntId());
        if (selectGood == null) {
            good.setSelectSum(1);
            selectedGoods.append(good.getIntId(), good);
        } else {
            int selectSum = selectGood.getSelectSum();
            selectGood.setSelectSum(++selectSum);
        }
        update(refresh);
    }

    /**
     * Item商品的购买数量减一
     *
     * @param good
     * @param refresh 是否刷新商品list
     */
    public void remove(Good good, boolean refresh) {
        int groupCount = selectedNumbers.get(good.getTypeId());
        if (groupCount == 1) {
            selectedNumbers.delete(good.getTypeId());
        } else if (groupCount > 1) {
            selectedNumbers.append(good.getTypeId(), --groupCount);
        }
        Good selectGood = selectedGoods.get(good.getIntId());
        if (selectGood != null) {
            if (selectGood.getSelectSum() < 2) {
                selectedGoods.remove(selectGood.getIntId());
            } else {
                int selectSum = selectGood.getSelectSum();
                selectGood.setSelectSum(--selectSum);
            }
        }
        update(refresh);
    }

    /**
     * 刷新界面 总价、购买数量等
     *
     * @param refresh 是否刷新商品list
     */
    public void update(boolean refresh) {
      /*L.d("总价：" + getTotalPrice());
        L.d("总数：" + getTotalSum());
        L.d("分类总数：" + getSelectedGroupCountByTypeId(1));
        L.d("商品的采购数量：" + getSelectedItemCountById(12));*/
        getShopCartDialog().changeView();
        for (OnChangeListener listener : listeners) {
            listener.changeView();
        }
    }

    //获得已选中商品的总价格
    public String getTotalPrice() {
        Double price = 0d;
        for (int i = 0; i < selectedGoods.size(); i++) {
            Good good = selectedGoods.valueAt(i);
            if (good.isWeighGood()) {
                if (good.getUnit().equals("500克")) {
                    price += Double.valueOf(good.getPrice()) * (Double.valueOf(good.getWeigh()) / 500);
                } else {
                    price += Double.valueOf(good.getPrice()) * Double.valueOf(good.getWeigh());
                }
            } else {
                price += Double.valueOf(good.getPrice()) * getSelectedItemCountById(good.getIntId());
            }
        }
        return PriceUtil.formatDouble(price);
    }

    //获得已选中商品的总数
    public String getTotalSum() {
        int sum = 0;
        for (int i = 0; i < selectedNumbers.size(); i++) {
            sum += selectedNumbers.valueAt(i);
        }
        return String.valueOf(sum);
    }

    //根据商品id获取当前商品的采购数量
    public int getSelectedItemCountById(int id) {
        Good good = selectedGoods.get(id);
        if (good == null) {
            return 0;
        }
        return good.getSelectSum();
    }

    //根据商品id获取当前商品的采购数量
    public Double getSelectedItemWeighById(int id) {
        Good good = selectedGoods.get(id);
        if (good == null) {
            return 0d;
        }
        return good.getWeigh();
    }


    //根据类别Id获取属于当前类别的数量
    public int getSelectedGroupCountByTypeId(int typeId) {
        return selectedNumbers.get(typeId);
    }

    /**
     * 清空选中商品
     */
    public void clearShopCart() {
        for (int i = 0; i < selectedGoods.size(); i++) {
            Good good = selectedGoods.valueAt(i);
            good.setSelectSum(0);
            if (good.isWeighGood()) {
                good.setWeigh(0d);
            }
        }
        selectedGoods.clear();
        selectedNumbers.clear();
        update(true);
    }

    /**
     * 商品管理重置
     */
    public void reset() {
        goods.clear();
        goodsTypes.clear();
        selectedGoods.clear();
        selectedNumbers.clear();
        listeners.clear();
        goodService.deleteAll();
        shopCartDialog = null;
    }

    //购物车是否空
    public boolean isEmptySelectedGood() {
        return selectedGoods.size() == 0;
    }

    //获得选中商品
    public SparseArray<Good> getSelectedGoods() {
        return selectedGoods;
    }

    public List<Good> getSelectedGoodList() {
        List<Good> arrayList = new ArrayList<>();
        for (int i = 0; i < selectedGoods.size(); i++) {
            arrayList.add(selectedGoods.valueAt(i));
        }
        return arrayList;
    }

    //获取所有商品
    public List<Good> getGoods() {
        return goods;
    }

    //获取商品分类
    public List<GoodsType> getGoodsTypes() {
        return goodsTypes;
    }

    //数据库
    public GoodService getGoodService() {
        return goodService;
    }

}
